<script setup>
    import {ref} from 'vue'
    import useUserInfoStore from '@/stores/userInfo.js'
    import {useTokenStore} from '@/stores/token.js'
    import { ElMessage, ElMessageBox } from 'element-plus';
    import {useRouter} from 'vue-router'
    import {districtPageQueryService, districtInfoUpdateService, districtDeleteService, districtInfoGetService, districtRegisterService, districtTreeQueryService} from '@/api/district.js'
    import { parseDistrictTree, districtTypeList, getDistrictTypeName } from '@/utils/district.js'
    import DistrictPositionPicker from './DistrictPositionPicker.vue';

    const uploadRef = ref()
    const userInfoStore = useUserInfoStore();
    const tokenStore = useTokenStore();
    const router = useRouter();


    
    //列表的物品总数
    const itemsTotal = ref(1);

    //片区分页查询的表单结构
    const districtPageQueryData = ref({
        page: 1,
        pageSize: 5,
        id: null,
        name: null,
        type: null,      
        parentId: null,
        positionId: null,
        deviceAmount: null,
        repairmanAmount: null,
    })

    const district = ref([])

    
//定义表单校验规则
const rules = {
    name: [
        { required: true, message: '片区名不能为空', trigger: 'blur' },
    ],
    parentId: [
        { required: true, message: '父片区不能为空', trigger: 'blur' },
    ],
}

    //分页查询获取用户列表
    const getdistrict = async()=>{
        console.log('get')
        let result = await districtPageQueryService(districtPageQueryData.value);
        district.value = result.records
        itemsTotal.value = result.total
        for(let i = 0;i < district.value.length; i++){
            district.value[i].typeName = getDistrictTypeName(district.value[i])
        }
        getdistrictTree()
    }

    const parsedDistrictTreeData = ref([{
        value: '1',
        label: '测试',
        children: [
            {
                value: '2',
                label: '测试2',
            }
        ]
    }])

    //树状查询获取用户列表
    const getdistrictTree = async()=>{
        let result = await districtTreeQueryService(-1);
        let tree = result.data
        parsedDistrictTreeData.value = parseDistrictTree(tree)
        
    }

    //页面加载时获取一次所有片区
    getdistrict()
    
    //分页大小改变时重新分页查询
    const handleSizeChange = (val) => {
        districtPageQueryData.value.pageSize = val
        getdistrict()
    }
    //分页页码改变时重新分页查询
    const handleCurrentChange = (val) => {
        districtPageQueryData.value.page = val
        getdistrict()
    }

    //是否在编辑，若为true则呼出右侧编辑窗口
    const isEditing = ref(false)
    //当前片区，用于承载编辑用户与添加用户的表单
    const currentDistrict = ref({})

    const updateDistrictInfo = async ()=>{
    //调用接口
    let result = await districtInfoUpdateService(currentDistrict.value);
    ElMessage.success(result.msg? result.msg : '修改成功');
    }

    //图片上传成功的回调函数

    //编辑用户
    const editDistrict = async (row) =>{
        isEditing.value = true   
        let result = await districtInfoGetService(row.id)
        currentDistrict.value = result.data;
    }

    //删除用户使用ElMessageBox判断
    const deleteDistrict = (row) =>{
        ElMessageBox.confirm(
            '要删除该片区吗?',
            'Warning',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }).then( async () => {
                let id = row.id;
                let result = await districtDeleteService(id)
                ElMessage.success(result.msg? result.msg : '删除成功');
                getdistrict()
        }).catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })

    }

    //取消编辑
    const cancelClickEditing = () =>{
        isEditing.value = false
    }

    //提交编辑
    const confirmClickEditing = async () =>{
        await updateDistrictInfo()
        isEditing.value = false
        await getdistrict()
    }

    //是否在添加新用户，若为true则呼出右侧新增用户窗口
    const isAdding = ref(false)

    const adddistrict = async() => {
         //调用接口
        let result = await districtRegisterService(currentDistrict.value);
        ElMessage.success(result.msg? result.msg : '新增成功');
        await getdistrict()
    }

    
    //添加新用户，初始化currentDistrict表单
    const adddistrictButton = () =>{
        currentDistrict.value = {
            id: 0,
            name: '',
            parentId: '',
            positionId: '',
            deviceAmount: null,
            repairmanAmount: null,
        }
        isAdding.value = true;
    }

    //取消新增用户
    const cancelClickAdding = () =>{
        isAdding.value = false
    }

    //提交新增用户
    const confirmClickAdding = async () =>{
        await adddistrict()
        isAdding.value = false
        getdistrict()
    }

    const isPicking = ref(false)
    
    const openPositionPicker = () =>{
        isPicking.value = true;
    }

    const setPosition = (e) =>{
        if(e){
            console.log(e)
            currentDistrict.value.longitude = e.lng
            currentDistrict.value.latitude = e.lat
        }
        isPicking.value = false;
    }


</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>片区管理</span>
            </div>
        </template>

        <div>
            <!-- 顶部栏，包含分页查询过滤条件，以及创建新用户 -->
            <el-form class="search-filter" :model="districtPageQueryData">
                <el-form-item label="片区名称">
                    <el-input v-model="districtPageQueryData.name" type="text"></el-input>
                </el-form-item>
                <el-form-item label="类型">
                    <el-select
                        v-model="districtPageQueryData.type"
                        placeholder="选择片区类型"
                        clearable
                        size="large"
                        >
                            <el-option
                            v-for="item in districtTypeList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                            />
                        </el-select>
                </el-form-item>
                <el-form-item label="所属父片区">
                    <el-tree-select
                        v-model="districtPageQueryData.parentId"
                        :data="parsedDistrictTreeData"
                        check-strictly
                        clearable
                        :render-after-expand="false"
                        style="width: 240px"
                    />
                </el-form-item>
                <el-form-item>
                        <el-button type="primary" @click="getdistrict">搜索</el-button>
                </el-form-item>
                <el-form-item>
                        <el-button @click="adddistrictButton">新增片区</el-button>
                </el-form-item>
            </el-form>
        </div>

        <hr style="background-color: #eee; height: 1px; border: none;"/>

        <!-- 用户表格 -->
        <el-table :data="district" style="width: 100%">
            <el-table-column prop="id" label="ID" width="180" sortable  />
            <el-table-column prop="name" label="片区名称" width="180" sortable  />
            <el-table-column prop="typeName" label="类型" sortable />
            <el-table-column prop="parentName" label="所属父片区" sortable />
            <el-table-column prop="positionId" label="坐标ID" sortable />
            <el-table-column prop="devDrkSum" label="饮水机数量" sortable />
            <el-table-column prop="devMakSum" label="制水机数量" sortable />
            <el-table-column prop="repmanAmount" label="维修人员数量" sortable />
            <el-table-column prop="chkmanAmount" label="运维人员数量" sortable />
            <el-table-column prop="operations" label="操作" fixed="right">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="editDistrict(scope.row)">编辑</el-button>
                    <el-button link type="danger" size="small" @click="deleteDistrict(scope.row)">删除</el-button>
                </template>
            </el-table-column>

        </el-table>

        <!-- 页码切换组件 -->
        <div class="pagination-block">
            <el-pagination layout="prev, pager, next, sizes" :total="itemsTotal" :page-size="districtPageQueryData.pageSize"
            v-model:current-page="districtPageQueryData.page"
            v-model:page-size="districtPageQueryData.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"/>
        </div>
    </el-card>

    <!-- 编辑用户的侧边界面 -->
    <el-drawer v-model="isEditing" :direction="rtl" size="50%">
        <template #header>
            <h4>编辑 {{ currentDistrict.name }} 信息</h4>
        </template>
        <template #default>
            <div class="form-edit-user" >
                <el-row>
                    <el-col :span="18">
                        <el-form :model="currentDistrict" :rules="rules" label-width="150px" size="large">
                            <el-form-item label="ID">
                                <el-input v-model="currentDistrict.id" disabled></el-input>
                            </el-form-item>
                            <el-form-item label="片区名称" prop="name">
                                <el-input v-model="currentDistrict.name"></el-input>
                            </el-form-item>
                            <el-form-item label="所属父片区" prop="parentId">
                                <el-tree-select
                                    v-model="currentDistrict.parentId"
                                    :data="parsedDistrictTreeData"
                                    check-strictly
                                    :render-after-expand="false"
                                    style="width: 240px"
                                />
                            </el-form-item>
                            <el-form-item label="经度" prop="longitude">
                                <el-input v-model="currentDistrict.longitude"></el-input>
                            </el-form-item>
                            <el-form-item label="纬度" prop="latitude">
                                <el-input v-model="currentDistrict.latitude"></el-input>
                            </el-form-item>
                            <el-form-item label="" prop="position">
                                <el-button @click="openPositionPicker">地图选点</el-button>
                            </el-form-item>
                        </el-form>
                    </el-col>
                </el-row>
            </div>
        </template>
        <template #footer>
        <div style="flex: auto">
            <el-button @click="cancelClickEditing">取消</el-button>
            <el-button type="primary" @click="confirmClickEditing">确认</el-button>
        </div>
        </template>
        
  </el-drawer>

  <el-dialog v-model="isPicking">
    <template #header>
            地图选点
    </template>
    <DistrictPositionPicker @exit="setPosition" />
  </el-dialog>

  <!-- 新增用户的侧边界面 -->
  <el-drawer v-model="isAdding" :direction="rtl" size="50%">
        <template #header>
            <h4>新增片区</h4>
        </template>
        <template #default>
            <div class="form-edit-user" >
                <el-row>
                    <el-col :span="18">
                        <el-form :model="currentDistrict" :rules="rules" label-width="150px" size="large">
                            <el-form-item label="片区名称" prop="name">
                                <el-input v-model="currentDistrict.name"></el-input>
                            </el-form-item>
                            <el-form-item label="所属父片区" prop="parentId">
                                <el-tree-select
                                    v-model="currentDistrict.parentId"
                                    :data="parsedDistrictTreeData"
                                    check-strictly
                                    :render-after-expand="false"
                                    style="width: 240px"
                                />
                            </el-form-item>
                            <el-form-item label="经度" prop="longitude">
                                <el-input v-model="currentDistrict.longitude"></el-input>
                            </el-form-item>
                            <el-form-item label="纬度" prop="latitude">
                                <el-input v-model="currentDistrict.latitude"></el-input>
                            </el-form-item>
                            <el-form-item label="" prop="position">
                                <el-button @click="openPositionPicker">地图选点</el-button>
                            </el-form-item>
                        </el-form>
                    </el-col>
                </el-row>
            </div>
        </template>
        <template #footer>
        <div style="flex: auto">
            <el-button @click="cancelClickAdding">取消</el-button>
            <el-button type="primary" @click="confirmClickAdding">确认</el-button>
        </div>
        </template>
  </el-drawer>


</template>

<style scoped>
    .search-filter {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
    }

    .pagination-block{
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .form-edit-user {
        display: flex;
        flex-direction: column;
        justify-content: center;
    }

    .form-edit-user-avatar {
        display: flex;
        justify-content: center;
        padding: 32px;
    }
    
</style>
